package com.clever.mall.service.impl;

import com.clever.mall.commons.dto.TwoUserRequestParam;
import com.clever.mall.commons.dto.UserRequestParam;
import com.clever.mall.commons.dto.UserUpdateRequestParam;
import com.clever.mall.commons.exception.UserException;
import com.clever.mall.commons.result.*;
import com.clever.mall.entity.User;
import com.clever.mall.mapper.*;
import com.clever.mall.service.UploadService;
import com.clever.mall.service.UserInfoService;
import com.clever.mall.utils.MyBeanUtils;
import com.clever.mall.utils.StatusCode;
import com.clever.mall.vo.ProductVo;
import com.clever.mall.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;

/**
 * @author ChenWang
 * @className UserInfoServiceImpl
 * @date 2020/11/09 15:24
 * @since JDK 1.8
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {
    @Resource
    private UserSocialContactMapper userSocialContactMapper;
    @Resource
    private UserOrderStatisticMapper userOrderStatisticMapper;
    @Resource
    private UserSellStatisticMapper userSellStatisticMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private UploadService uploadService;
    @Resource
    private ProductVoMapper productVoMapper;

    /**
     * 根据指定的用户（ID 或名字）查询用户信息
     * @param userRequestParam  指定的用户
     * @return                  指定的用户信息
     */
    @Override
    public UserVo getUserVo(UserRequestParam userRequestParam) {
        User user = new User();
        BeanUtils.copyProperties(userRequestParam,user);
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(userMapper.selectUserByUser(user),userVo);
        return userVo;
    }

    /**
     * 获取指定用户的粉丝用户集合
     * @param userRequestParam  指定的用户
     * @return      粉丝集合
     */
    @Override
    public List<UserVo> getFansList(UserRequestParam userRequestParam) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        return commonUserList(userRequestParam,"selectFansList");
    }

    /**
     * 获取指定用户的关注用户集合
     * @param userRequestParam  指定的用户
     * @return      关注集合
     */
    @Override
    public List<UserVo> getAttentionList(UserRequestParam userRequestParam) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        return commonUserList(userRequestParam,"selectAttentionList");
    }

    /**
     * 通用型的查询用户的关注或者粉丝
     * @param userRequestParam      指定的参数名
     * @param name                  指定的方法名
     * @return                      返回用户集合
     * @throws InvocationTargetException    调用方法异常
     * @throws IllegalAccessException       权限
     * @throws NoSuchMethodException        指定的方法不存在
     */
    private List<UserVo> commonUserList(UserRequestParam userRequestParam, String name) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        User user = new User();
        BeanUtils.copyProperties(userRequestParam,user);
        Method method = userSocialContactMapper.getClass().getMethod(name,User.class);
        method.setAccessible(true);
        List<User> users = (List<User>) method.invoke(userSocialContactMapper,user);
        List<UserVo> userVos = MyBeanUtils.copyListProperties(users, UserVo::new);
        return userVos;
    }

    /**
     * 根据传入的用户参数查询用户的个人主页信息
     * @param userRequestParam      传入的用户参数
     * @return  对应的主页信息
     */
    @Override
    public UserMyPage getUserMyPage(UserRequestParam userRequestParam){
        UserMyPage userMyPage = new UserMyPage();
        User user= new User();
        BeanUtils.copyProperties(userRequestParam,user);
        /*user中只需要id*/
        userMyPage.setUserId(user.getUserId());
        /*关注用户的数量*/
        userMyPage.setAttention(userSocialContactMapper.selectAttention(user));
        /*粉丝的数量*/
        userMyPage.setFans(userSocialContactMapper.selectFans(user));
        /*没看的信息数目*/
        int note = userSocialContactMapper.selectAllNotViewMessage(user);
        /*设置有多少条未读消息*/
        userMyPage.setNote(note);
        /*设置未查看的买入的统计数据*/
        userMyPage.setUserOrderStatistic(selectUserOrderStatistic(user));
        /*设置未查看的卖出的统计数据*/
        userMyPage.setUserSellStatistic(selectUserSellStatistic(user));
        /*获取指定user的全部数据*/
        User theUser = userMapper.selectUserByUser(user);
        /*
         * 判定用户是否存在
         */
        if(Objects.isNull(theUser)){
            throw new UserException(StatusCode.USER_NOT_EXIST_ERROR);
        }
        UserVo userVo = getUserVo(theUser);
        userMyPage.setUserVo(userVo);
        /*返回*/
        return userMyPage;
    }

    /**
     * 获取我的个人主页信息
     * @param userRequestParam  指定的user
     * @param page              页码
     * @param size              页面大小
     * @return                  页面信息
     */
    @Override
    public UserHomePage getUserHomePage(UserRequestParam userRequestParam,int page,int size) {
        /*获取我的主页的基本信息*/
        UserHomePage userHomePage = new UserHomePage();
        userHomePage.setUserMyPage(getUserMyPage(userRequestParam));
        User user = new User();
        BeanUtils.copyProperties(userRequestParam,user);
        /*获取我的在售商品信息*/
        /*List<Product> onSaleProducts = productMapper.selecOnSaletByUser(user, page, size);*/
        /*获取我的已经售卖的商品信息*/
        /*List<Product> SoldOutProducts = productMapper.selectBeenSoldByUser(user, page, size);*/
        /*copy到vo中*/
        /*List<ProductVo> onSaleProductVos = MyBeanUtils.copyListProperties(onSaleProducts, ProductVo::new);*/
        /*List<ProductVo> SoldOutProductVos = MyBeanUtils.copyListProperties(SoldOutProducts, ProductVo::new);*/
        /*获取我的在售商品信息*/
        List<ProductVo> onSaleProductVos = productVoMapper.selecOnSaletByUser(user, page, size);
        /*获取我的已经售卖的商品信息*/
        List<ProductVo> SoldOutProductVos = productVoMapper.selectBeenSoldByUser(user,page,size);
        /*放到userHomePage中*/
        userHomePage.setOnSaleProductVos(onSaleProductVos);
        userHomePage.setSoldOutproductVos(SoldOutProductVos);
        return userHomePage;
    }

    /**
     * 获取指定用户的消息
     * @param userRequestParam     指定的用户
     * @return  指定的用户的消息
     */
    @Override
    public MessagePage getMessagePage(UserRequestParam userRequestParam) {
        /*List list = new ArrayList();
        List newList = new ArrayList();
        list.stream().sorted().forEach(newList::add);*/
        User user = new User();
        BeanUtils.copyProperties(userRequestParam,user);
        List<MessageAttentionResult> messageAttentionResults = userSocialContactMapper.selectAttentionByUser(user);
        List<MessageOrderResult> messageOrderResults = userSocialContactMapper.selectOrderByUser(user);
        MessagePage messagePage = new MessagePage();
        messagePage.setMessageAttentionResults(messageAttentionResults);
        messagePage.setMessageOrderResults(messageOrderResults);
        return messagePage;
    }

    /**
     * 查询他人的信息主页的信息
     * @param twoUserRequestParam     被查询者
     * @param page                      页码
     * @param size                      大小
     * @return                          他人主页信息
     */
    @Override
    public OtherUserHomePage getOtherUserHomePage(TwoUserRequestParam twoUserRequestParam, int page, int size) {
        /*用户请求数据*/
        UserRequestParam userRequestParam = twoUserRequestParam.getUserRequestParam();
        /*他人用户的请求数据*/
        UserRequestParam otherUserRequestParam = twoUserRequestParam.getOtherUserRequestParam();
        /*实例化他人个人主页信息类*/
        OtherUserHomePage otherUserHomePage = new OtherUserHomePage();
        /*获取他人个人首页的数据信息*/
        otherUserHomePage.setUserHomePage(getUserHomePage(otherUserRequestParam,page,size));
        /*设置关注状态：如果是游客则默认设置为0*/
        if(Objects.isNull(userRequestParam)||Objects.isNull(userRequestParam.getUserId())){
            otherUserHomePage.setIsAttention(0);
        }else {
            /*当前用户*/
            User user = new User();
            user.setUserId(userRequestParam.getUserId());
            /*他人用户*/
            User otherUser = new User();
            otherUser.setUserId(otherUserRequestParam.getUserId());
            /*在他人用户个人首页浏览的当前用户的ID*/
            otherUserHomePage.setUserId(userRequestParam.getUserId());
            /*查询当前用户是否关注过当前浏览的他人用户*/
            int isAttention = userSocialContactMapper.selectAttentionRelation(user,otherUser);
            /*设置关注状态*/
            otherUserHomePage.setIsAttention(isAttention);
        }
        return otherUserHomePage;
    }

    /**
     * 改变对他人的关注状态
     *
     * @param twoUserRequestParam@return                          改变状态是否成功
     */
    @Override
    public int changeAttention(TwoUserRequestParam twoUserRequestParam) {
        UserRequestParam userRequestParam = twoUserRequestParam.getUserRequestParam();
        UserRequestParam otherUserRequestParam = twoUserRequestParam.getOtherUserRequestParam();
        /*判定关注者的ID是否存在--是否是游客*/
        if(Objects.isNull(userRequestParam)||Objects.isNull(userRequestParam.getUserId())){
            /*是游客抛出用户权限异常*/
            throw new UserException(StatusCode.USER_TOURIEST_ERROR);
        }
        User user = new User();
        User otherUser = new User();
        user.setUserId(userRequestParam.getUserId());
        otherUser.setUserId(otherUserRequestParam.getUserId());
        /*根据ID获取对应用户信息*/
        user = userMapper.selectUserByUser(user);
        otherUser = userMapper.selectUserByUser(otherUser);
        /*判断用户是否存在*/
        if(Objects.isNull(user)||Objects.isNull(otherUser)){
            /*不存在就抛出用户不存在异常*/
            throw new UserException(StatusCode.USER_NOT_EXIST_ERROR);
        }
        /* 判定是否曾经关注过以及关注关注状态
        *   查询是否有关注记录
        *   0表示没有--没有查询到记录
        *   1表示正在关注
        *   2表示不再关注
        *   3表示该条数据已删除
        * */
        int status = userSocialContactMapper.selectAttentionRelationExist(user, otherUser);
        int flag ;
        if (0 != status) {
            /*1表示关注,2表示不再关注*/
            status = status!=1?1:2;
            flag = userSocialContactMapper.updateAttentionRelation(user,otherUser,status);
        } else {
            /*如果不曾关注过，那么状态改变就是新插入关注关系，并且默认为关注*/
            flag = userSocialContactMapper.insertAttentionRelation(user,otherUser);
        }
        return flag;
    }

    @Override
    public int updateUserInfo(UserUpdateRequestParam userUpdateRequestParam) throws IOException {
        User user = new User();
        user.setUserId(userUpdateRequestParam.getUserId());
        user = userMapper.selectUserByUser(user);
        if(Objects.isNull(user)){
            throw new UserException(StatusCode.USER_NOT_EXIST_ERROR);
        }
        String path = uploadService.uploadImg(userUpdateRequestParam.getIcon());
        userUpdateRequestParam.setUserIcon(path);
        BeanUtils.copyProperties(userUpdateRequestParam,user);
        return userMapper.updateUser(user);
    }

    /**
     * 更具用户查询用户订单统计数据
     * @param user  指定的用户
     * @return  用户订单统计信息
     */
    private UserOrderStatistic selectUserOrderStatistic(User user){
        UserOrderStatistic userOrderStatistic = new UserOrderStatistic();
        /*设置用户ID*/
        userOrderStatistic.setUserId(user.getUserId());
        /*根据状态码获取用户的购买订单信息*/
        userOrderStatistic.setRequiredPay(userOrderStatisticMapper.selectOrderStaticByUserAndStatus(user,0));
        userOrderStatistic.setRequiredDeliver(userOrderStatisticMapper.selectOrderStaticByUserAndStatus(user,1));
        userOrderStatistic.setRequiredReceive(userOrderStatisticMapper.selectOrderStaticByUserAndStatus(user,2));
        userOrderStatistic.setFinish(userOrderStatisticMapper.selectOrderStaticByUserAndStatus(user,3));
        return userOrderStatistic;
    }
    /**
     * 更具用户查询用户售卖统计数据
     * @param user  指定的用户
     * @return  用户售卖产品统计信息
     */
    private UserSellStatistic selectUserSellStatistic(User user){
        UserSellStatistic userSellStatistic = new UserSellStatistic();
        /*设置用户ID*/
        userSellStatistic.setUserId(user.getUserId());
        /*未查看的审核信息数量*/
        userSellStatistic.setCheck(userSellStatisticMapper.selectCheckStatisticByUser(user));
        /*未查看的在售中的商品信息数量*/
        userSellStatistic.setOnSale(userSellStatisticMapper.selectOnSaleStatisticByUser(user));
        /*未查看的已售出的商品数量*/
        userSellStatistic.setBeenSold(userSellStatisticMapper.selectBeenSoldStatisticByUser(user));
        /*未查看的已退回的商品数量*/
        userSellStatistic.setReturnBack(userSellStatisticMapper.selectReturnBackStatisticByUser(user));
        return userSellStatistic;
    }

    /**
     * 根据指定的user获取对应的UserVo
     * @param user  指定的user数据
     * @return      返回对应 UserVo
     */
    private UserVo getUserVo(User user){
        UserVo userVo = new UserVo();
        /*指定展示数据*/
        BeanUtils.copyProperties(user,userVo);
        /*返回*/
        return userVo;
    }
}
